package com.css.fxfzdzzh.web.interceptor;

import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.util.PlatformHttpRequestUtils;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.base.response.ResponseCode;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.base.syssubapp.repository.entity.SysSubappEntity;
import com.css.fxfzdzzh.base.syssubapp.service.SysSubappService;
import com.css.fxfzdzzh.util.PlatformJwtUtils;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.util.PlatformRSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author wenyugang
 * @Date 2020/4/26
 * @Version 1.0.0
 * @Description
 */
@Slf4j
@Component
public class ApiInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RestResponse restResponse = null;

        //===============================================================================================================
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(FxfzConstants.CUR_USER_ID_IN_SESSION);
        if (PlatformObjectUtils.isNotEmpty(userId)) {// userId 存在
            log.debug("当前登录用户,userId={}", userId);
            PlatformSessionContext.setUserID(userId);
            return true;
        } else {
            // userId不存在
            session.invalidate();
            if (PlatformHttpRequestUtils.isAjax(request)) {
                log.debug("用户未登录,请求为ajax请求");
                response.getWriter().write("{\"code\":\"401\"}");
            } else {
                log.debug("用户未登录,跳转到登录页");
                response.sendRedirect("http://10.13.155.117:8081/login");
            }
        }
        //===============================================================================================================
        String token = request.getHeader("token");
        String appTokenId = request.getHeader("appTokenId");
        String appCode = request.getHeader("appCode");

        if (!PlatformObjectUtils.isEmpty(token) && PlatformJwtUtils.isJwtValid(token)) {
            PlatformSessionContext.setUserID(PlatformJwtUtils.getUserFromToken(token));
            return true;
        } else if(PlatformObjectUtils.isNotEmpty(appTokenId)&&PlatformObjectUtils.isNotEmpty(appCode)){
            ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            SysSubappService sysSubappService = context.getBean(SysSubappService.class);
            SysSubappEntity sysSubappEntity = sysSubappService.findByCode(appCode);
            if (PlatformObjectUtils.isNotEmpty(sysSubappEntity)){
                String privateKey=sysSubappEntity.getPrivateKey();
                String decryptAppToken = PlatformRSAUtils.decrypt(appTokenId, privateKey);
                if (decryptAppToken.equals(sysSubappEntity.getTokenId())){
                    return true;
                }else{
                    return false;
                }
            }else {
                return false;
            }
        }else {
            restResponse = RestResponse.fail(ResponseCode.UNAUTHORIZED, "invalid token");
            response.getWriter().write(restResponse.toString());
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        PlatformSessionContext.removeUserID();
    }
}
